package com.yangyongchao.dailyassistant.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.yangyongchao.dailyassistant.R;
import com.yangyongchao.dailyassistant.amap.activity.EmulatorActivity;
import com.yangyongchao.dailyassistant.amap.activity.RideActivity;
import com.yangyongchao.dailyassistant.feature.Callback;
import com.yangyongchao.dailyassistant.utils.UpdateAppUtils;
import com.yangyongchao.dailyassistant.view.ConfirmDialog;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements AMapLocationListener {
    //当前经度
    public static double NowLatitude;
    //当前纬度
    public static double NowLongitude;
    //目标经度
    public static double DestinationLatitude = 24.8388+0.5;
    //目标纬度
    public static double DestinationLongitude = 102.852+0.5;
    //现在的街道信息
    public static String NowStreet;

    private String TGA = "MainActivity";
    private double StartLatitude;
    private double StartLongitude;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    //public AMapLocationListener mLocationListener = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    private Button btn_ems,btn_ride,btn_update,btn_car,btn_robot,btn_wechat;
    private ImageView welcome;
    private int code = 3;
    //图片的绝对地址
    private String url = "https://unsplash.it/240/200/?random";
    //服务器apk path,这里放了百度云盘的apk 作为测试
    String apkPath = "http://issuecdn.baidupcs.com/issue/netdisk/apk/BaiduNetdisk_7.15.1.apk";


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_ems = (Button) findViewById(R.id.btn_ems);
        btn_ride = (Button) findViewById(R.id.btn_ride);
        btn_update = (Button) findViewById(R.id.btn_update);
        btn_car = (Button) findViewById(R.id.btn_car);
        btn_robot = (Button) findViewById(R.id.btn_robot);
        btn_wechat = (Button) findViewById(R.id.btn_wechat);
        welcome = (ImageView) findViewById(R.id.iv_welcome);

        btn_ems.setOnClickListener(new onclick ());
        btn_ride.setOnClickListener(new onclick ());
        btn_update.setOnClickListener(new onclick ());
        btn_car.setOnClickListener(new onclick ());
        btn_robot.setOnClickListener(new onclick ());
        btn_wechat.setOnClickListener(new onclick ());

        initLocation();

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Bitmap bmp = getURLimage(url);
                Message msg = new Message();
                msg.what = 0;
                msg.obj = bmp;
                handle.sendMessage(msg);
            }
        }).start();
        //Glide.with(MainActivity.this).load("https://unsplash.it/400/400/?random").into(welcome);
    }


    @Override
    protected void onResume() {
        super.onResume();
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Bitmap bmp = getURLimage(url);
                Message msg = new Message();
                msg.what = 0;
                msg.obj = bmp;
                handle.sendMessage(msg);
            }
        }).start();
    }

    private class onclick  implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.btn_ems:
                    Intent intent = new Intent(MainActivity.this,EmsActivity.class);
                    startActivity(intent);
                    break;

                //跳转到模拟汽车导航界面
                case R.id.btn_car:
                    intent = new Intent(MainActivity.this, EmulatorActivity.class);
                    intent.putExtra("mStartLatitude",StartLatitude);
                    intent.putExtra("mStartLongitude",StartLongitude);
                    startActivity(intent);
                    break;
                case R.id.btn_update:
                    checkAndUpdate(3);
                    break;
                //开启模拟骑行导航
                case R.id.btn_ride:
                    startActivity(new Intent(MainActivity.this, RideActivity.class));
                    break;
                case R.id.btn_robot:
                    break;
                case R.id.btn_wechat:
                    break;
                default:
                    break;
            }
        }
    }
    //在消息队列中实现对控件的更改
    private Handler handle = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    System.out.println("111");
                    Bitmap bmp=(Bitmap)msg.obj;
                    welcome.setImageBitmap(bmp);
                    break;
            }
        };
    };
    public Bitmap getURLimage(String url) {
        Bitmap bmp = null;
        try {
            URL myurl = new URL(url);
            // 获得连接
            HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
            conn.setConnectTimeout(6000);//设置超时
            conn.setDoInput(true);
            conn.setUseCaches(false);//不缓存
            conn.connect();
            InputStream is = conn.getInputStream();//获得图片的数据流
            bmp = BitmapFactory.decodeStream(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bmp;
    }

    private void checkAndUpdate(int code) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            realUpdate(code);
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                realUpdate(3);
            } else {//申请权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }
    }


    private void realUpdate(int code) {
        this.code = code;
        switch (code) {
            case 3:
                update3();
        }
    }
    //强制更新
    private void update3() {
        UpdateAppUtils.from(this)
                .serverVersionCode(2)
                .serverVersionName("2.0")
                .apkPath(apkPath)
                .isForce(true)
                .update();
    }

    //权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    realUpdate(code);
                } else {
                    new ConfirmDialog(this, new Callback() {
                        @Override
                        public void callback(int position) {
                            if (position==1){
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.parse("package:" + getPackageName())); // 根据包名打开对应的设置界面
                                startActivity(intent);
                            }
                        }
                    }).setContent("暂无读写SD卡权限\n是否前往设置？").show();
                }
                break;
        }
    }

//    public void changeImageView(View view) {
//        if (!isExpand) {
//            isExpand = true;
//            final Handler mHandler = new Handler() {
//                @Override
//                public void handleMessage(Message msg) {
//                    super.handleMessage(msg);
//                    if (msg.what == CHANGE_LEVEL) {
//                        int level = mClipDrawable.getLevel() + 50;
//                        if (level >= 10000) {
//                            level = 10000;
//                        }
//                        mClipDrawable.setLevel(level);
//                    }
//                }
//            };
//            final CountDownTimer timer = new CountDownTimer(Integer.MAX_VALUE, 10) {
//                @Override
//                public void onTick(long millisUntilFinished) {
//
//                    if (mClipDrawable.getLevel() >= 10000) {
//                        this.onFinish();
//                    } else {
//                        mHandler.sendEmptyMessage(99);
//                    }
//
//                }
//
//                @Override
//                public void onFinish() {
//                    isExpand = false;
//                }
//            };
//            timer.start();
//        }
//    }
//
//    public void changeImage(View view) {
//        if (welcome.getDrawable() != null) {
//            welcome.setBackground(welcome.getDrawable());
//        }
//        Drawable drawable =new BitmapDrawable(getURLimage(url));
//        final ClipDrawable imageDrawable = new ClipDrawable(drawable,
//                Gravity.TOP | Gravity.START, ClipDrawable.VERTICAL);
//        welcome.setImageDrawable(imageDrawable);
//        imageDrawable.setLevel(10);
//        if (!isExpand) {
//            isExpand = true;
//            final Handler mHandler = new Handler() {
//                @Override
//                public void handleMessage(Message msg) {
//                    super.handleMessage(msg);
//                    if (msg.what == CHANGE_LEVEL) {
//                        int level = imageDrawable.getLevel() + 50;
//                        if (level >= 10000) {
//                            level = 10000;
//                        }
//                        imageDrawable.setLevel(level);
//                    }
//                }
//            };
//            final CountDownTimer timer = new CountDownTimer(Integer.MAX_VALUE, 10) {
//                @Override
//                public void onTick(long millisUntilFinished) {
//
//                    if (imageDrawable.getLevel() >= 10000) {
//                        this.onFinish();
//                    } else {
//                        mHandler.sendEmptyMessage(99);
//                    }
//                }
//
//                @Override
//                public void onFinish() {
//                    isExpand = false;
//                }
//            };
//            timer.start();
//        }
//    }
    /**
     * 对当前位置进行定位，获取当前位置的坐标信息
     */
    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //设置定位参数
        mLocationClient.setLocationOption(getDefaultOption());
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mLocationClient.startLocation();
    }

    /**
     *    定位成功后回调的方法,更新全局的当前位置
     *
     * @param aMapLocation  返回的定位对象
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if(aMapLocation != null){
            if(aMapLocation.getErrorCode() == 0){
                //定位成功回调信息，设置相关消息
                //解析定位结果,在主线程中执行的
                //Log.i(TAG, "线程2："+Thread.currentThread());
                /*aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                aMapLocation.getCountry();//国家信息
                aMapLocation.getProvince();//省信息
                aMapLocation.getCity();//城市信息
                aMapLocation.getDistrict();//城区信息
                aMapLocation.getStreet();//街道信息
                aMapLocation.getStreetNum();//街道门牌号信息
                aMapLocation.getCityCode();//城市编码
                aMapLocation.getAdCode();//地区编码
                aMapLocation.getAoiName();//获取当前定位点的AOI信息
                aMapLocation.getAccuracy();//获取精度信息*/
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(aMapLocation.getTime());
                df.format(date);//定位时间
                StartLatitude = aMapLocation.getLatitude();
                NowLatitude = StartLatitude;
                StartLongitude = aMapLocation.getLongitude();
                NowLongitude = StartLongitude;
                NowStreet = aMapLocation.getStreet();//街道信息
                Log.e(TGA, "经度："+StartLatitude+"---------------"+"纬度:"+ StartLongitude+"-------------街道信息:"+NowStreet);
                /*tv_location_data.setText("纬度：" + mCurrentLatitude
                        + "经度：" + mCurrentLongitude);*/
            }else{
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError","location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    }


    /**
     * 默认的定位参数
     *
     */
    private AMapLocationClientOption getDefaultOption(){

        AMapLocationClientOption mOption = new AMapLocationClientOption();
        //设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setGpsFirst(false);
        //设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setHttpTimeOut(30000);
        //设置定位间隔。默认为2秒
        mOption.setInterval(2000);
        //设置是否返回逆地理地址信息。默认是true
        mOption.setNeedAddress(true);
        //设置是否单次定位。默认是false
        mOption.setOnceLocation(false);
        //设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        mOption.setOnceLocationLatest(false);
        //设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);
        //设置是否使用传感器。默认是false
        mOption.setSensorEnable(false);
        //设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setWifiScan(true);
        //设置是否使用缓存定位，默认为true
        mOption.setLocationCacheEnable(true);

        return mOption;
    }
}
